package model

import (
	"fmt"

	"gorm.io/gorm"
)

type Comment struct {
	CommentID       int            `gorm:"primaryKey; autoIncrement"`
	ParentCommentID int            `gorm:"null"`
	PassageID       int            `gorm:"not null"`
	CommentUserID   int            `gorm:"not null"`
	CommentContent  string         `gorm:"not null"`
	CommentType     int            `gorm:"not null"` // 1-顶级评论 2-子评论
	CommentReplyID  int            `gorm: "null"`    //评论的回复ID（父级评论ID）
	DeletedAt       gorm.DeletedAt `gorm:"index"`
	Passage         *Passage       `gorm:"foreignKey:PassageID"`
}

type ReplyComment struct {
	ParentCommentID       int
	CommentID             int
	CommentUserName       string
	CommentUserID         int
	CommentUserPhoto      string
	CommentContent        string
	CommentParentUserName string
	CommentParentUserID   int
	CommentLikeCount      int
	CommentType           int
}

// 根据顶级评论查找所有同一块评论
func GetChildernComments(parentcomment_id int) ([]ReplyComment, error) {
	var err error
	var ChildrenComments []ReplyComment
	var comments []Comment
	err = DB.Model(Comment{}).Where("ParentCommentID = ?", parentcomment_id).Find(&comments).Error
	if err != nil {
		return nil, err
	}
	//填充好每一个评论消息的详细信息
	for _, comment := range comments {
		var reply_comment ReplyComment
		//评论的内容
		reply_comment.CommentContent = comment.CommentContent
		reply_comment.CommentID = comment.CommentID
		reply_comment.CommentType = comment.CommentType
		//评论的作者ID
		reply_comment.CommentUserID = comment.CommentUserID
		//评论的用户名
		user, err := GetUserMiniByID(comment.CommentUserID)
		if err != nil {
			return nil, err
		}
		reply_comment.CommentUserName = user.UName
		reply_comment.CommentUserPhoto = user.ProfilePhoto
		//首先跟据父级评论ID查找到评论者的ID
		parent_user_id, err := GetCommentUserID(comment.CommentReplyID)
		if err != nil {
			//说明该条评论的父对象已经被删除了
			reply_comment.CommentParentUserName = "该评论已被删除"
			reply_comment.CommentParentUserID = -1
			//评论的点赞数
			reply_comment.CommentLikeCount, err = GetCommentLikeCount(comment.CommentID)
			if err != nil {
				return nil, err
			}
			ChildrenComments = append(ChildrenComments, reply_comment)
			continue
			// return nil, err
		}
		//根据查找到的父级评论的作者的ID，再次查询评论的父级用户名
		parent_user, err := GetUserMiniByID(parent_user_id)
		if err != nil {
			//说明该条评论的父对象已经被删除了
			reply_comment.CommentParentUserName = "该评论已被删除"
			reply_comment.CommentParentUserID = -1
			//评论的点赞数
			reply_comment.CommentLikeCount, err = GetCommentLikeCount(comment.CommentID)
			if err != nil {
				return nil, err
			}
			ChildrenComments = append(ChildrenComments, reply_comment)
			continue
			// return nil, err
		}
		reply_comment.CommentParentUserName = parent_user.UName
		reply_comment.CommentParentUserID = parent_user.UserID
		//评论的点赞数
		reply_comment.CommentLikeCount, err = GetCommentLikeCount(comment.CommentID)
		if err != nil {
			return nil, err
		}
		ChildrenComments = append(ChildrenComments, reply_comment)
	}
	return ChildrenComments, nil
}

// 根据文章ID返回顶级评论
func GetCommentByID(id int) (string, error) {
	var err error
	var comment string

	err = DB.Model(Comment{}).Select("CommentContent").Where("CommentID = ? AND CommentType = 1", id).Find(&comment).Error
	if err != nil {
		return comment, err
	}
	return comment, nil
}

func GetCommentsByPaID(id int) ([]Comment, error) {
	var err error
	var comments []Comment
	err = DB.Model(Comment{}).Where("PassageID = ? AND CommentType = 1", id).Find(&comments).Error
	if err != nil {
		return comments, err
	}
	return comments, nil
}

func GetReplyComments(id int) ([]Comment, error) {
	var err error
	var replies []Comment
	err = DB.Model(Comment{}).Where("CommentReplyID = ?", id).Find(&replies).Error
	if err != nil {
		return replies, err
	}
	return replies, nil
}

// 根据评论的ID查找对应的评论者的ID
func GetCommentUserID(comment_id int) (int, error) {
	var err error
	var user_id int
	err = DB.Model(Comment{}).Select("CommentUserID").Where("CommentID = ?", comment_id).Find(&user_id).Error
	if err != nil {
		return user_id, err
	}
	return user_id, nil
}

func GetPassageIDByCommentID(comment_id int) (int, error) {
	var passage_id int
	err := DB.Model(Comment{}).Select("PassageID").Where("CommentID = ?", comment_id).Find(&passage_id).Error
	if err != nil {
		return passage_id, err
	}
	return passage_id, nil
}

func UploadComment(comment Comment) (int, error) {
	cerr := DB.Model(&Comment{}).Create(&comment).Error
	if cerr != nil {
		return -1, cerr
	}
	uerr := DB.Model(&Passage{}).Where("PassageID = ?", comment.PassageID).UpdateColumn("CommentNum", gorm.Expr("CommentNum + ?", 1)).Error
	if uerr != nil {
		return -1, cerr
	}
	return comment.CommentID, nil
}

func DeleteComment(cid int) error {
	// 获取文章id（一定要先获取再删评！）
	var passageID int
	err := DB.Model(&Comment{}).Where("CommentID = ?", cid).Select("PassageID").Scan(&passageID).Error
	if err != nil {
		return err
	}
	fmt.Println("文章id: ", passageID)

	var uerr error
	var parentCommentID int
	perr := DB.Model(&Comment{}).Where("CommentID = ?", cid).Select("ParentCommentID").Scan(&parentCommentID).Error
	if perr != nil {
		return perr
	}
	fmt.Println("顶级评论id: ", parentCommentID)
	if parentCommentID != 0 {
		uerr = DB.Model(&Passage{}).Where("PassageID = ?", passageID).UpdateColumn("CommentNum", gorm.Expr("CommentNum - ?", 1)).Error
	} else {
		var count int64
		ccerr := DB.Model(&Comment{}).Where("ParentCommentID = ?", cid).Count(&count).Error
		if ccerr != nil {
			return ccerr
		}
		fmt.Println("子评论数量: ", count)
		uerr = DB.Model(&Passage{}).Where("PassageID = ?", passageID).UpdateColumn("CommentNum", gorm.Expr("CommentNum - ?", count+1)).Error
	}
	if uerr != nil {
		return uerr
	}

	cerr := DB.Where("CommentID = ?", cid).Delete(&Comment{}).Error
	return cerr
}

func GetCommentAllByID(cid int) (Comment, error) {
	var comment Comment
	err := DB.Model(&Comment{}).Where("CommentID = ?", cid).Take(&comment).Error
	if err != nil {
		return comment, err
	}
	return comment, nil
}
